import time

from fastapi.encoders import jsonable_encoder
from starlette import status
from starlette.responses import RedirectResponse, JSONResponse
from fastapi import FastAPI, Request, HTTPException
from sqlmodel import SQLModel

from core.globals import site
from core.settings import settings
from backend.apps.common import DemoException,ApiResult

app = FastAPI(debug=settings.debug)

# 注意1: site.mount_app会默认添加site.db的session会话上下文中间件,如果你使用了其他的数据库连接,请自行添加.例如:
# from core.globals import sync_db
# app.add_middleware(sync_db.asgi_middleware) # 注意中间件的注册顺序.

# 注意2: 非请求上下文中,请自行创建session会话,例如:定时任务,测试脚本等.
# from core.globals import async_db
# async with async_db():
#     async_db.async_get(...)
#     async_db.session.get(...)
#     # do something

@app.exception_handler(HTTPException)  # 重写HTTPException异常处理器
async def http_exception_handler(request, exc):
    print("{}, {}".format(exc.err_code, exc.err_msg))
    return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(ApiResult(code=exc.err_code, msg=exc.err_msg)))


@app.middleware("http")
async def token_check(request: Request, call_next):
    start_time = time.time()
    token = request.headers.get("token")
    # if not token:
    #     return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(ApiResult(code=400, msg="token错误!")))
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


@app.on_event("startup")
async def startup():
    await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)
    pass



@app.get('/')
async def index():
    raise DemoException(err_msg="测试错误！！！")
    return RedirectResponse(url=site.router_path)


# 安装应用
from apps import demo
demo.setup(app.router,site)
from apps import category
category.setup(app.router,site)

# 挂载后台管理系统
site.mount_app(app)


if __name__ == '__main__':
    import uvicorn

    uvicorn.run(app)